
public class AudioParser implements IParser {
	
	private AudioFile audioFile;
	
	public AudioParser(AudioFile audioFile){
		this.audioFile = audioFile;
	}
	
	@Deprecated
	private double[] convertBigSoundData(byte[] src){
		int offset = 0;
		double[] dest = new double[src.length/2];
		for(int i=0; i<dest.length; i++){
			int sample =
				  (src[offset + 0] << 8)
				| (src[offset + 1] & 0xFF);
			offset += 2;
			dest[i] = sample;
		}
		return dest;
	}

	@Deprecated
	private double[] convertLittleSoundData(byte[] src){
		int offset = 0;
		double[] dest = new double[src.length/2];
		for(int i=0; i<dest.length; i++){
			int sample =
				  (src[offset + 0] & 0xFF)
				| (src[offset + 1] << 8);
			offset += 2;
			dest[i] = sample;
		}
		return dest;
	}
	
	public double getSoundDataMean(byte[] data){
		if(audioFile.getAudioFormat().isBigEndian())
			return this.getBigSoundDataMean(data);
		else
			return this.getLittleSoundDataMean(data);
	}
	
	private double getBigSoundDataMean(byte[] data){
		double sum = 0;
		int offset = 0;
		for(int i=0; i<data.length/2; i++){
			int sample =
				  (data[offset + 0] << 8)
				| (data[offset + 1] & 0xFF);
			offset += 2;
			sum += Math.abs(sample);  //ABS
		}
		return sum/(data.length/2);  //return MAD
	}
	
	private double getLittleSoundDataMean(byte[] data){
		double sum = 0;
		int offset = 0;
		for(int i=0; i<data.length/2; i++){
			int sample =
				  (data[offset + 0] & 0xFF)
				| (data[offset + 1] << 8);
			offset += 2;
			sum += Math.abs(sample);  //ABS
		}
		return sum/(data.length/2);   //return MAD
	}

	@Override
	public void parse(VideoSegment[] segments) {

		try {
			System.out.println("Audio information parsing starts");
			double maxWeight = 0;
			for(int i=0; i<segments.length; ++i){
				if (segments[i] == null)
					continue;
				
				//Set the start position
				audioFile.setPositionBasedOnVideo(segments[i].start);				
				byte[] rawBuffer = audioFile.readDurationSoundData(segments[i].getLength() );
				if(rawBuffer == null)
					continue;
				double weight = Math.abs(getSoundDataMean(rawBuffer));
				segments[i].setAudioWeight(weight);
				if (maxWeight < segments[i].audioWeight)
					maxWeight = segments[i].audioWeight;
			}
			for(int i=0; i<segments.length; i++){
				if(segments[i] != null)
					segments[i].audioWeight /= maxWeight;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
